<template>
  <div>
    <el-tag
      v-for="(item, index) in routeArr"
      :key="index"
      :type="activeIndex === index ? 'success' : ''"
      closable
      @click="pathHandle(item)"
      @close="del(item, index)"
    >{{ item }}</el-tag>
  </div>
</template>
<script>
export default {
  name: 'TagsView1',
  data() {
    return {
      routeArr: JSON.parse(localStorage.getItem('routeArr')) || [],
      activeIndex: 0
    }
  },
  computed: {},
  watch: {
    '$route.path': {
      handler: function(newVal, oldVal) {
        console.log(newVal, this.routeArr, 8)
        !this.routeArr.includes(newVal) && this.routeArr.push(newVal)
        localStorage.setItem('routeArr', JSON.stringify(this.routeArr))
        this.activeIndex = this.routeArr.findIndex((item) => item === newVal)
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    del(path, index) {
      console.log(path, 1)
      this.activeIndex = this.routeArr.findIndex((item) => item === path) - 1

      this.routeArr = this.routeArr.filter((item) => {
        return item !== path
      })
      if (this.activeIndex === -1) {
        this.$router.push('/')
      } else {
        this.$router.push(this.routeArr[this.activeIndex])
      }

      localStorage.setItem('routeArr', JSON.stringify(this.routeArr))
    },
    pathHandle(path, i) {
      this.$router.push(path)
      this.activeIndex = i
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag {
  margin: 5px;
}
</style>
